package com.wingscode.modules.sys.controller;

import com.wingscode.common.utils.PageUtils;
import com.wingscode.common.utils.R;
import com.wingscode.modules.common.entity.ChatDetailEntity;
import com.wingscode.modules.common.entity.ChatObjectEntity;
import com.wingscode.modules.common.service.ChatDetailService;
import com.wingscode.modules.common.service.ChatObjectService;
import com.wingscode.modules.sys.form.ChatContentForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * 沟通管理
 *
 * @author yan
 */
@RestController
@RequestMapping("/chat")
public class ChatController extends AbstractController {
	@Autowired
	private ChatObjectService chatObjectService;
	@Autowired
	private ChatDetailService chatDetailService;

	
	/**
	 * 平台沟通列表
	 */
	@PostMapping("/list")
	public R list(@RequestParam Map<String, Object> params){
		if (!params.containsKey("type"))
			return R.error("type为空");

		PageUtils page = chatObjectService.queryObject(params);

		return R.ok().put("page", page);
	}

	/**
	 * 发送聊天
	 */
	@PostMapping("/save")
	public R save(@RequestBody ChatContentForm form){
		if (form.getContentType() == null)
			return R.error("contentType为空");
		if (form.getChatId() == null)
			return R.error("chatId为空");
		if (form.getUserId() == null)
			return R.error("userId为空");
		if (form.getContent().isEmpty() && form.getImgUrl().isEmpty())
			return R.error("content或imgUrl为空");

		// 更新聊天对象最后消息
		ChatObjectEntity chatObject = chatObjectService.getById(form.getChatId());
		if (chatObject != null) {
			chatObject.setState(1);
			if (form.getContentType() == 0)
				chatObject.setLastContent(form.getContent());
			else
				chatObject.setLastImg(form.getImgUrl());
			chatObject.setLastTime(new Date());
			chatObject.setToUserId(form.getUserId());

			chatObjectService.updateById(chatObject);

			// 设置消息已读
			ChatDetailEntity entity = new ChatDetailEntity();
			entity.setChatId(chatObject.getId());
			entity.setFromAgentId(chatObject.getFromAgentId());
			entity.setIsRead(1);

			chatDetailService.updateByFromAgent(entity);
		}

		// 保存聊天消息
		ChatDetailEntity chatDetail = new ChatDetailEntity();
		chatDetail.setChatId(form.getChatId());
		chatDetail.setToUserId(form.getUserId());
		chatDetail.setType(form.getContentType());
		chatDetail.setContent(form.getContent());
		chatDetail.setImgUrl(form.getImgUrl());
		chatDetail.setIsRead(0);
		chatDetail.setCreateTime(new Date());

		chatDetailService.save(chatDetail);

		return R.ok();
	}

	/**
	 * 获得聊天内容
	 */
	@GetMapping("/getChatDetail")
	public R getChatDetail(@RequestParam Map<String, Object> params){
		if (!params.containsKey("chatId"))
			return R.error("chatId为空");

		PageUtils page = chatDetailService.getDetail(params);

		return R.ok(200, page);
	}


}
